package org.kkhweb.checkbook;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;

public class main extends Activity {

	private SharedPreferences settings;
	private Editor editor;
	private SimpleJSONParser jsonParser;
	private SimpleFiles files;
	private SimpleHTTPClient httpClient;
	private ProgressDialog dialog;
	private Map<Integer,String> checkbookIDs;
	
	public static final String CHECKBOOKS_FILE = "Checkbooks_JSON_File";
    public static final String PREFS_NAME = "MyCheckbookSettings";
	private static final int DIALOG_CHECKBOOK_LIST = 0;
	private static final int DIALOG_PREFERRED = 1;
	
	private Intent signin;
	private Intent createNew;
	private Intent preferences;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       
        this.restore_settings();
        
    	signin = new Intent(this, SignInActivity.class);
    	createNew = new Intent(this, CreateNewActivity.class);
    	preferences = new Intent(this, PreferencesActivity.class);        
        
        final ImageView books_list_button = (ImageView) findViewById(R.id.books_list);
        books_list_button.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
            	books_list_button.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
            	showDialog(DIALOG_CHECKBOOK_LIST);
                return true;
            }
        });

        final ImageView books_create_button = (ImageView) findViewById(R.id.books_create);
        this.createNew = new Intent(this, CreateNewActivity.class);
        books_create_button.setOnTouchListener(new OnTouchListener() {
        	@Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
            	books_create_button.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
                startActivity(createNew);
                return true;
            }
        });

        final ImageView quick_trans_withdraw_button = (ImageView) findViewById(R.id.quick_trans_withdraw);
        quick_trans_withdraw_button.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
            	quick_trans_withdraw_button.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
            	toast("Quick Withdraw");
                return true;
            }
        });

        final ImageView quick_trans_deposit_button = (ImageView) findViewById(R.id.quick_trans_deposit);
        quick_trans_deposit_button.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
            	quick_trans_deposit_button.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
            	toast("Quick Deposit");
                return true;
            }
        });
        
        final ImageView set_preferred_button = (ImageView) findViewById(R.id.tools_preferred);
        set_preferred_button.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
            	set_preferred_button.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
            	showDialog(DIALOG_PREFERRED);
                return true;
            }
        });          
    }

    @Override
    protected void onStop(){
    	super.onStop();
    }
        
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        	case R.id.opt_sync:
        		if(settings.getBoolean("logged_in", false)) {
        			syncThread();
        		} else {
        			toast("You Must Signin to Sync Your Account");
        		}
        		return true;
        	case R.id.opt_signin:
        		startActivity(this.signin);
        		return true;           		
	        case R.id.opt_settings:	        	
	        	startActivity(this.preferences);
	            return true;	            	            
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }    
    
	@Override
    protected Dialog onCreateDialog(int id)
    {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
        switch(id) {
        case DIALOG_CHECKBOOK_LIST:
        	final CharSequence[] checkbooks = buildCheckbookList();
        	if(checkbooks == null) {
        		dialog = null;
        	} else {
	        	builder.setTitle("Checkbook");
				builder.setItems(checkbooks, new DialogInterface.OnClickListener() {
	        	    public void onClick(DialogInterface dialog, int item) {
	        	    	editor.putString("viewing_account", checkbookIDs.get(item));
	        	        toast(checkbookIDs.get(item));
	        	    }
	        	});
	        	dialog = builder.create();
        	}
            break;
        case DIALOG_PREFERRED:
        	final CharSequence[] preferred = buildCheckbookPreferredList();
        	 if(preferred == null) {
         		dialog = null;
         	} else {
	        	builder.setTitle("Choose Preferred Checkbook");
	        	builder.setSingleChoiceItems(preferred, -1, new DialogInterface.OnClickListener() {
	        	    public void onClick(DialogInterface dialog, int item) {
	        	        toast((String) preferred[item]);
	        	    }
	        	});
	        	dialog = builder.create();
         	}
            break;
        default:
            dialog = null;
        }
        return dialog;
    }
    
//Sync Thread    
	protected void syncThread()
	{
		httpClient = new SimpleHTTPClient();
		
    	dialog = ProgressDialog.show(main.this, "Syncing With Server", 
                "Please wait...", false);  		    

	    new Thread() {
			@Override
		    public void run()
		    {         
				int userID = settings.getInt("user_id", 0);
		    	httpClient.addFormData("user_id", Integer.toString(userID));
		    	httpClient.setURL(Globals.buildURL("get_books"));
		    	httpClient.sendRequest();
		        
		        syncHandler.sendEmptyMessage(0);
		    }
	    }.start();
	}        

//Handler for SyncThread    
	private Handler syncHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			dialog.dismiss();
    		
    		if(httpClient.hasError()) {
    			toast(httpClient.getError());
    		} else {
    			files = new SimpleFiles(getApplicationContext());
    			files.saveFile(CHECKBOOKS_FILE, httpClient.getResponse());
    			if(files.hasError()) {
    				toast(files.getError());
    			} else {
    				toast("Checkbook Sync Complete");
    			}
    		}
		}
	};		
	
	private CharSequence[] buildCheckbookList()
	{
		ArrayList<String> bookslist = new ArrayList<String>();
		String jsonCheckbooks = "";
		checkbookIDs = new HashMap<Integer, String>();
    	jsonParser = new SimpleJSONParser();        	
    	
		files = new SimpleFiles(getApplicationContext());
		files.readFile(CHECKBOOKS_FILE);
		if(files.hasError()) {
			toast(files.getError());
            return null;
		} else {
			jsonCheckbooks = files.getOutput();
			
	    	jsonParser.parse(jsonCheckbooks);
	    	
	        if(jsonParser.hasError()) {               	
	            toast(jsonParser.getError());
	            return null;
	        } else {
	            if(jsonParser.size() == 1) {
	            	checkbookIDs.put(1, jsonParser.getStr("id"));
	            	bookslist.add(jsonParser.getStr("name")+" ($"+jsonParser.getStr("balance")+")");
	            } else {
	                for(int a = 0; a < jsonParser.size(); a++) {
	                	checkbookIDs.put(a, jsonParser.getStr(a, "id"));
	                	bookslist.add(jsonParser.getStr(a, "name")+" ($"+jsonParser.getStr(a, "balance")+")");
	                }
	            }
	        }
		}
        final CharSequence[] checkbooks = bookslist.toArray(new CharSequence[bookslist.size()]);
        return checkbooks;
	}
	
	private CharSequence[] buildCheckbookPreferredList()
	{
		ArrayList<String> bookslist = new ArrayList<String>();
		String jsonCheckbooks = "";
		checkbookIDs = new HashMap<Integer, String>();		
    	jsonParser = new SimpleJSONParser();        	
    	
		files = new SimpleFiles(getApplicationContext());
		files.readFile(CHECKBOOKS_FILE);
		if(files.hasError()) {
			toast(files.getError());
            return null;			
		} else {
			jsonCheckbooks = files.getOutput();
	
	    	jsonParser.parse(jsonCheckbooks);
	    	
	        if(jsonParser.hasError()) {               	
	            toast(jsonParser.getError());
	            return null;
	        } else {
	            if(jsonParser.size() == 1) {
                	checkbookIDs.put(1, jsonParser.getStr("id"));
	            	bookslist.add(jsonParser.getStr("name"));
	            } else {
	                for(int a = 0; a < jsonParser.size(); a++) {
	                	checkbookIDs.put(a, jsonParser.getStr(a, "id"));
	                	bookslist.add(jsonParser.getStr(a, "name"));
	                }
	            }
	        }
		}
        final CharSequence[] checkbooks = bookslist.toArray(new CharSequence[bookslist.size()]);
        return checkbooks;
	}	
	
//Toast Messages    
    private void toast(String msg)
    {
    	Context context = getApplicationContext();
    	Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();    	
    }	
	
	private void restore_settings()
	{
        // Restore preferences
        settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        editor = settings.edit();        
	}
	
}